import 'package:flutter_admin/models/user_info.dart';
import 'package:flutter_admin/pages/common/cry/cry_button.dart';
import 'package:flutter_admin/pages/common/cry/cry_button_bar.dart';
import 'package:flutter_admin/pages/common/cry/cry_buttons.dart';
import 'package:flutter_admin/pages/common/cry/form/cry_input.dart';
import 'package:flutter_admin/pages/common/cry/form/cry_select.dart';
import 'package:flutter_admin/pages/common/cry/model/order_item_model.dart';
import 'package:flutter/material.dart';
import 'package:flutter_admin/pages/common/cry/cry_data_table.dart';
import 'package:flutter_admin/api/odoo/stock_quant_odoo_api.dart';
import 'package:flutter_admin/constants/enum.dart';
import 'package:flutter_admin/pages/common/cry/model/page_model.dart';
import 'package:flutter_admin/pages/common/cry/model/response_body_api.dart';
import 'package:flutter_admin/models/odoo/stock_quant.dart';
import 'package:flutter_admin/pages/odoo/stock_quant/stock_quant_dialog.dart';
import 'package:flutter_admin/pages/common/cry/utils/cry_utils.dart';
import 'package:flutter_admin/pages/common/cry/vo/select_option_vo.dart';
import 'package:flutter_admin/api/odoo/dynamic_data_api.dart';
import 'package:flutter_admin/pages/odoo/stock_quant/team_stock_qunat/team_stock_quant_consume.dart';
import 'package:flutter_admin/utils/adaptive_util.dart';
import 'package:flutter_admin/utils/store_util.dart';
import 'package:flutter_admin/utils/utils.dart';
import 'package:quiver/strings.dart';

class TeamStockQuantList extends StatefulWidget {
  TeamStockQuantList({Key? key}) : super(key: key);

  @override
  _TeamStockQuantListState createState() => _TeamStockQuantListState();
}

class _TeamStockQuantListState extends State<TeamStockQuantList> {
  final GlobalKey<CryDataTableState> tableKey = GlobalKey<CryDataTableState>();
  final GlobalKey<FormState> formKey = GlobalKey<FormState>();
  final GlobalKey<ScaffoldState> scaffoldStateKey = GlobalKey<ScaffoldState>();
  PageModel page =
      PageModel(orders: [OrderItemModel(column: 'create_date', asc: false)]);
  StockQuant stockQuant = StockQuant();
  List<StockQuant> selectedList = [];
  //仓库位置id
  List<SelectOptionVO> locationIdList = [];
  //车间名称
  // List<SelectOptionVO> workshopIdList = [];

  // String? workshopId;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance!.addPostFrameCallback((c) {
      // _query();
      _loadSelectVO();
    });
  }

  _loadSelectVO() async {
    UserInfo userInfo = StoreUtil.getCurrentUserInfo();
    if (userInfo.major != null) {
      locationIdList = await DynamicDataApi.getModelSelect(
          // active: false,
          model: "stock.location",
          name: "complete_name",
          key: "team_id",
          operator: "!=",
          val: null);
    } else {
      locationIdList = await DynamicDataApi.getModelSelect(
          // active: false,
          model: "stock.location",
          name: "complete_name",
          key: "team_id",
          operator: "!=",
          val: null,
          key2: 'workshop_id',
          val2: int.parse(userInfo.deptId!));
      // workshopId = userInfo.deptId;
    }
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    UserInfo userInfo = StoreUtil.getCurrentUserInfo();
    var form = Form(
      key: formKey,
      child: Wrap(
        children: <Widget>[
          CrySelect(
            label: '库房位置',
            width: 380,
            dataList: locationIdList,
            value: stockQuant.locationId,
            onSaved: (v) => {stockQuant.locationId = v},
          ),
          CryInput(
            width: 160,
            label: '物料编码',
            value: stockQuant.productCode,
            onSaved: (v) {
              stockQuant.productCode = v;
            },
          ),
          CryInput(
            width: 160,
            label: '物料名称',
            value: stockQuant.productName,
            onSaved: (v) {
              stockQuant.productName = v;
            },
          ),
        ],
      ),
    );

    CryDataTable table = CryDataTable(
      key: tableKey,
      title: "数据列表",
      // actions: !isDisplayDesktop(context)
      //     ? [
      //         _operationList(),
      //       ]
      //     : [],
      onPageChanged: (firstRowIndex) {
        page.current = (firstRowIndex ~/ page.size + 1);
        _loadData();
      },
      onRowsPerPageChanged: (int size) {
        page.size = size;
        page.current = 1;
        _loadData();
      },
      onSelectChanged: (Map selected) {
        this.setState(() {});
      },
      columns: [
        DataColumn(label: Text('仓库位置')),
        DataColumn(label: Text('生产单号')),
        DataColumn(label: Text('物料编号')),
        DataColumn(label: Text('物料名称')),
        DataColumn(label: Text('材质型号')),
        DataColumn(label: Text('批次号')),
        DataColumn(label: Text('库存数量')),
        DataColumn(label: Text('计量单位')),
        DataColumn(label: Text('作业员')),
        DataColumn(label: Text('操作时间')),
      ],
      getCells: (m) {
        StockQuant stockQuant = StockQuant.fromMap(m);
        return [
          DataCell(Text(stockQuant.locationName ?? '--')),
          DataCell(Text(stockQuant.productorderno ?? '--')),
          DataCell(Text(stockQuant.productCode ?? '--')),
          DataCell(Text(stockQuant.productName ?? '--')),
          DataCell(Text(stockQuant.productDes ?? '--')),
          DataCell(Text(stockQuant.batchno ?? '--')),
          DataCell(Text(stockQuant.quantity.toString())),
          DataCell(Text(stockQuant.productUomName ?? '--')),
          DataCell(Text(stockQuant.username ?? '--')),
          DataCell(Text(Utils.timeUTC(stockQuant.createDate) ?? '--')),
        ];
      },
    );
    _getSelectList();
    CryButtonBar buttonBar = CryButtonBar(
      children: <Widget>[
        CryButtons.query(context, () => _query()),
        CryButtons.reset(context, () => _reset()),
        CryButton(
            label: "库存消耗",
            iconData: Icons.construction,
            onPressed:
              selectedList.length == 1
                  ? () => _consume(selectedList[0])
                  : null
        ),
      ],
    );
    var result = Scaffold(
      key: scaffoldStateKey,
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          SizedBox(height: 10),
          Wrap(
            children: [
              form,
              Padding(
                padding: EdgeInsets.only(top: 24),
                child: buttonBar,
              )
            ],
          ),
          Expanded(child: SingleChildScrollView(child: table)),
        ],
      ),
    );
    return result;
  }

  _consume(StockQuant? stockQuant) async {
    showDialog(
      barrierDismissible: false,
      context: context,
      builder: (BuildContext context) => Dialog(
        child: TeamStockQuantCoume(
          stockQuant: stockQuant!,
        ),
      ),
    ).then((v) {
      if (v != null) {
        _loadData();
      }
    });
  }

  _reset() {
    stockQuant = StockQuant();
    formKey.currentState!.reset();
    // workshopId = null;
    // workshopIdList = [];
    // locationIdList = [];
    tableKey.currentState?.pageTo(0);
    tableKey.currentState!.loadData(PageModel());
    setState(() {});
  }

  _query() {
    formKey.currentState?.save();
    tableKey.currentState?.pageTo(0);
    _loadData();
  }

  _loadData() async {
    if (isBlank(stockQuant.locationId)) {
      tableKey.currentState?.pageTo(0);
      tableKey.currentState!.loadData(PageModel());
      CryUtils.message("请选择库房位置");
      return;
    }
    ResponseBodyApi responseBodyApi = await StockQuantOdooApi.page(data: {
      "page": page,
      "domainList": stockQuant.toDomainList(),
    });
    if (responseBodyApi.success!) {
      page = responseBodyApi.data != null ? responseBodyApi.data : PageModel();
      tableKey.currentState!.loadData(page);
      _getSelectList();
    }
  }

  // _search() {
  //   return showDialog(
  //     context: context,
  //     builder: (BuildContext context) => Dialog(
  //       child: StockQuantDialog(),
  //     ),
  //   ).then((v) {
  //     if (v != null) {
  //       stockQuant = v;
  //       _query();
  //     }
  //   });
  // }

  _getSelectList() {
    selectedList = tableKey.currentState
            ?.getSelectedList(page)
            .map<StockQuant>((e) => StockQuant.fromMap(e))
            .toList() ??
        [];
    setState(() {});
  }

  // _operationList() {
  //   return PopupMenuButton(
  //     onSelected: (dynamic v) {
  //       if (v == OperationType.query) {
  //         _search();
  //       }
  //     },
  //     itemBuilder: (context) => <PopupMenuEntry<OperationType>>[
  //       PopupMenuItem<OperationType>(
  //         value: OperationType.query,
  //         child: ListTile(
  //           leading: const Icon(Icons.search),
  //           title: Text('查询'),
  //         ),
  //       ),
  //     ],
  //   );
  // }
}
